package com.prj.ufdm.cloud.ms.test.util;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.SQLException;

import org.apache.ibatis.jdbc.ScriptRunner;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.SqlSessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.prj.ufdm.cloud.base.exception.BaseException;
import com.prj.ufdm.cloud.ms.test.enums.MsTestRetCodeEnum;

/** 
* DESC: 数据库表工具类
* @date 2020年02月28日 
* @author 胡义振
*/
@Component
public class DbTableUtils {
	
	@Autowired
	SqlSessionTemplate sqlSessionTemplate;
	
	/**
	 * DESC: 执行SQL语句
	 * @auther 胡义振
	 * @date 2020年3月4日
	 * @param sql 
	 * @return
	 */
	public void executeSql(String sql) {
		Connection conn = null;
		try
		{
			Reader reader = new StringReader(sql);
			conn = SqlSessionUtils.getSqlSession(
					this.sqlSessionTemplate.getSqlSessionFactory(), 
					this.sqlSessionTemplate.getExecutorType(),
		            this.sqlSessionTemplate.getPersistenceExceptionTranslator()).getConnection();
			ScriptRunner runner = new ScriptRunner(conn);
//			runner.setAutoCommit(true);//自动提交
//			runner.setFullLineDelimiter(false);
//			runner.setDelimiter(";");//每条命令间的分隔符
//			runner.setSendFullScript(false);
//			runner.setStopOnError(false);
//			OutputStream os = new FileOutputStream("scriptLog.log");
//			PrintWriter logWriter = new PrintWriter(os);
//			runner.setLogWriter(logWriter);//设置是否输出日志
			runner.runScript(reader);
			conn.commit();
		}
		catch(Exception er) {
			System.out.println("\n 执行SQL发生异常：");
			er.printStackTrace();
			throw new BaseException(MsTestRetCodeEnum.RET_CODE_0999998.getCode(),MsTestRetCodeEnum.RET_CODE_0999998.getMessage());
		}
		finally {
			if(conn!=null) {
				try {
					conn.close();
				} catch (SQLException e) {
					System.out.println("\n 关闭连接发生异常：");
					throw new BaseException(MsTestRetCodeEnum.RET_CODE_0999998.getCode(),MsTestRetCodeEnum.RET_CODE_0999998.getMessage());
				}
			}
		}
	}
	
}
